package org.kgc.alanhealth.util;

import org.springframework.stereotype.Service;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Random;

@Service
public class SmsService {

    private final Map<String, String> codeMap = new ConcurrentHashMap<>();
    private final SmsUtils smsUtils;

    public SmsService(SmsUtils smsUtils) {
        this.smsUtils = smsUtils;
    }

    public String generateCode() {
        Random random = new Random();
        return String.format("%04d", random.nextInt(9000) + 1000);
    }

    public boolean sendSms(String phone, String signName, String templateCode) {
        try {
            String code = generateCode();
            String templateParam = "{\"code\":\"" + code + "\"}";
            smsUtils.sendSms(signName, templateCode, phone, templateParam);
            codeMap.put(phone, code);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean verifyCode(String phone, String code) {
        // 验证验证码是否正确
        String storedCode = codeMap.get(phone);
        if (storedCode != null && storedCode.equals(code)) {
            codeMap.remove(phone); // 验证成功后移除验证码
            return true;
        }
        return false;
    }
}